package com.itwn.portal.service.impl;

import com.itwn.common.constant.RedisConst;
import com.itwn.portal.mapper.BookMapper;
import com.itwn.portal.model.entity.Book;
import com.itwn.portal.model.vo.CartItemVo;
import com.itwn.portal.model.vo.CartVo;
import com.itwn.portal.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired(required = false)
    private BookMapper bookMapper;

    @Override
    public CartVo getCart(Long userId) {
        // 先从Redis中获取购物车对象
        String key = RedisConst.USER_CART_PREFIX + ":" + userId;
        ValueOperations<String,CartVo> valueOperations = redisTemplate.opsForValue();
        CartVo cartVo = valueOperations.get(key);
        if (cartVo == null) {
            // 如果Redis中没有，则创建一个空的购物车对象
            cartVo = new CartVo();
            cartVo.setUserId(userId);
        }
        // 将购物车对象存入Redis中
        valueOperations.set(key, cartVo);

        return cartVo;
    }

    @Override
    public CartVo addCart(long userId, Long bookId) {
        // 根据用户id查询购物车
        CartVo cartVo = this.getCart(userId);
        // 根据图书id查询
        Book book = bookMapper.selectById(bookId);
        // 添加到购物车对象
        cartVo.addItem(new CartItemVo(
                userId, bookId, book.getName(), book.getImgSrc(), book.getPrice(), 1));
        // 购物车key
        String key = RedisConst.USER_CART_PREFIX + ":" + userId;
        // 购物车存储到Redis中 （可以设置过期时间）
        redisTemplate.opsForValue().set(key, cartVo,7, TimeUnit.DAYS);
        return cartVo;
    }
}
